package com.ks.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ks.common.PageResult;
import com.ks.dto.PageQueryDTO;
import com.ks.entity.Rule;
import com.ks.mapper.RuleMapper;
import com.ks.service.RuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
@Slf4j
public class RuleServiceImpl extends ServiceImpl<RuleMapper, Rule> implements RuleService {

    @Autowired
    private RuleMapper ruleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init(){
        LambdaQueryWrapper<Rule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Rule> ruleList = ruleMapper.selectList(lambdaQueryWrapper);
        String jsonString = JSON.toJSONString(ruleList);
        //先删除redis中的rule数据
        stringRedisTemplate.delete("rule");
        // 保存到redis
        stringRedisTemplate.opsForValue().set("rule", jsonString);
        log.info("规则加载到redis");
//        String rule = stringRedisTemplate.opsForValue().get("rule");
//        List<Rule> ruleList1 = JSON.parseArray(rule, Rule.class);
//        System.out.println(ruleList1);
    }

    @Override
    public PageResult pageRule(PageQueryDTO pageQueryDTO) {
        IPage page = new Page(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        LambdaQueryWrapper<Rule> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        page = page(page, lambdaQueryWrapper);
        PageResult pageResult = PageResult.builder()
               .total(page.getTotal())
               .records(page.getRecords())
               .build();
        return pageResult;
    }

    @Override
    public void addRule(Rule rule) {
        ruleMapper.insert(rule);
        // 保存到redis
        init();
    }

    @Override
    public void deleteRule(Integer id) {
        ruleMapper.deleteById(id);
        // 保存到redis
        init();
    }

    @Override
    public void updateRule(Rule rule) {
        ruleMapper.updateById(rule);
        // 保存到redis
        init();
    }
}
